Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

226
Visualizações
how to fix this is node"Error: User validation failed: username: Path `username` is required. password: Path `password` is required."

I'm creating a new user and checking whether the user email previously exists or not. If not then it is creating a new user and saving it. What do I need to correct this validation error I am getting?

I have already tried by setting name as not required. But it still does not work.

This is my User model.

User.js

import mongoose from 'mongoose'

const UserSchema = new mongoose.Schema(
    {
      username: {
        type: String,
        required: true,
        unique: true,
      },
      email: {
        type: String,
        required: true,
        unique: true,
      },
      password: {
        type: String,
        required: true,
      },
      profilePic: {
        type: String,
        default: "",
      },
    },
    { timestamps: true }
  );

const User = mongoose.model("User",UserSchema)
export default User

this is my router file

import User from '../model/User.js'
import express from 'express'

const router = express.Router()

//register
router.post("/register",async (req,res) => {
    try{
        const newUser = new User({
            username:req.body.username,
            password:req.body.password,
            email:req.body.email
        })

        const user =await newUser.save()
        res.status(200).json(user)
    }catch(err){
        res.status(500).json(err)
    }
})

export default router

this is my app.js

import express from 'express'
import mongoose from 'mongoose'
import dotenv from 'dotenv'
import UserRoute from './routes/User.js'

const app = express()
dotenv.config()
app.use(express.json())
app.use(express.urlencoded({ extended: true }));

const PORT = process.env.PORT || 3000

mongoose
  .connect(process.env.MONGO_URL, {
    useNewUrlParser: true,
    useUnifiedTopology: true
  })
  .then(console.log("Connected to MongoDB"))
  .catch((err) => console.log(err));

app.use("/api/auth",UserRoute)

app.listen(PORT , () => console.log(`backend started on ${PORT}` ))

i also just notice one thing if i tries to bcrypt the password and then use it in my route then after making request in postman instead of error message i am getting null object {} in postman what's the reason ???

what is the issue on the code i tried different ways to fix this by taking reference from stack overflow but didn't work

thanks for your help

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

How is your request body look like? Are you sure there are req.body.username and req.body.passwords? Try console.log them before you save the user and check they are not undefined.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda